a<template>
  <div>
    <el-form :model="basicInfo" :rules="rules" ref="basicInfo" label-width="100px">
      <div class="detail-info" style="margin-top: 50px">
        <div class="form-item">
          <h4>基本信息</h4>
          <el-form-item label="分公司" required >
            <el-select v-if="!brachDisabled" v-model="basicInfo.banchid" :disabled="brachDisabled" style="width:220px">
              <el-option v-for="(item, index) in this.branchList" :value="item.branch_Id" :label="item.branch_Name" :key="index"></el-option>
            </el-select>
            <el-input v-if="brachDisabled" v-model="showBranch" :disabled="brachDisabled" style="width:220px"></el-input>
          </el-form-item>
          <el-form-item label="客资类型" required >
            <el-select v-model="basicInfo.usertype" style="width:220px" :loading="customerTypeLoading" placeholder="客资类型">
              <!-- <el-option value="1" label="普通超市"></el-option> -->
              <el-option v-for="(item, index) in customerTypeList"
              :key="index"
              :label="item.name"
              :value="item.id.toString()"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="广告类型" prop="markid">
            <el-select v-model="basicInfo.markid" @change="markidChange" placeholder="广告类型" style="width:220px">
              <el-option v-for="(item, index) in markidGroup" :value="item.markId" :label="item.name" :key="index" ></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="所属设备">
            <el-checkbox-group  v-model="equipments" @change="checkBoxChange">
              <el-checkbox v-for="(item, index) in equipmentsGroup" :label = "item" :key="item">{{item}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item> -->
          <el-form-item label="所属设备" prop="equipments">
            <el-radio-group v-model="basicInfo.equipments" @change="radioChange">
              <el-radio v-for="(item, index) in equipmentsGroup" :label="item.id" :key="index">{{item.name}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="广告名称" prop="cadname">
            <el-input v-model="basicInfo.cadname" placeholder="广告名称" style="width:220px"></el-input>
          </el-form-item>
          <el-form-item label="起止时间" prop="startStopTime">
            <el-date-picker v-model="basicInfo.startStopTime" placeholder="起止时间" :editable="false" :clearable="false"
            type="datetimerange" @change="daterangeFormat" value-format="yyyy-MM-dd-HH-mm-ss" style="width:350px"
            :picker-options="pickerExpirationDate"
                            :default-time="['00:00:00', '23:59:59']"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="basicInfo.cadmemo" type="textarea" placeholder="备注" style="width:220px"></el-input>
          </el-form-item>
        </div>
      </div>
      <div class="detail-info" style="margin-top: 50px;" v-if="actionTag">
        <div class="form-item" @click="divClick(0)">
          <h4>{{this.actionName}}</h4>
          <el-form-item label="图片选择" required >
            <el-upload
              class="avatar-uploader"
              :action="url"
              name="imageFile"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              accept=".jpg,.png">
              <img v-if="basicInfo.adPicture[0].adimage" :src="this.imgHost + '/' + basicInfo.adPicture[0].adimage" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="跳转方式" prop="radioModel">
            <el-radio-group v-model="basicInfo.radioModel" @change="actionChange">
              <el-radio v-for="(item, index) in actionGroup" :label="item.markId.toString()" :key="index">{{item.name}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <div style=" overflow:hidden">
          <el-form-item label="" v-if="basicInfo.radioModel !== '20'" style="float:left;margin-right:30px">
            <el-input v-model="basicInfo.adPicture[0].adurl" placeholder="请输入链接" style="width:220px" :disabled="inputDisabled"></el-input>
          </el-form-item>
          <el-form-item label="" v-if="basicInfo.radioModel === '10'" prop="activeId">
            <el-select v-model="basicInfo.activeId" @change="actionSelChange" style="width:220px;float:left">
              <el-option v-for="(item, index) in activeGroup" :label="item.activityName" :value="item.activityId.toString()" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="" v-if="basicInfo.radioModel === '40'" prop="pageId">
            <el-select v-model="basicInfo.pageId" @change="actionSelChange" style="width:220px;float:left">
              <el-option v-for="(item, index) in pageGroup" :label="item.name" :value="item.markId" :key="index"></el-option>
            </el-select>
          </el-form-item>
          </div>
        </div>
      </div>
    </el-form>
    <div style="margin: 20px auto 20px;width:20%">
      <el-button @click="onSubmit(2, 'basicInfo')" type="success">提交</el-button>
      <el-button @click="onSubmit(1, 'basicInfo')" type="warning">暂存</el-button>
      <el-button @click="cancel(menuId, 1)" type="danger">取消</el-button>
    </div>
  </div>
</template>
<script>
  import Vue from 'vue'
  import { gggl, getInfo, column } from '../../../../../config/proxy.js'
  import { apiHost, apiURL } from '../../../../../config/settings.js'
  import mixins from '../../../../../components/mixins.vue'
  export default {
    mixins: [mixins],
    data () {
      return {
        pickerExpirationDate: { // 截止日期类型禁用时间段
          disabledDate (time) {
            return time.getTime() < Date.now() - 8.64e7
          }
        },
        basicInfo: {
          banchid: '', // 分公司
          usertype: '1', // 客资类型
          markid: '', // 广告类型
          equipment: [], // 所属设备
          cadname: '', // 广告名称
          orderuptime: '', // 开始时间
          offlinetime: '', // 结束时间
          cadmemo: '', // 备注
          adPicture: [
            {
              actiontype: '', // 跳转方式
              actionName: '', // 跳转方式名称
              actionId: '', // 跳转id
              adimage: '', // 图片路径
              adurl: '', // 动作参数
              equipment: '' // 所属设备
            }
          ],
          radioModel: '', // radioModel
          equipments: '', // 所属设备中间变量
          startStopTime: '', // 起止时间
          activeId: '',
          pageId: ''
        },
        equipmentsGroup: [], // 所属设备数组
        showBranch: [],
        brachDisabled: false,
        customerTypeLoading: false, // 客资类型loading
        customerTypeList: [], // 客资类型数组
        markidGroup: [], // 广告类型数组
        actionGroup: [], // 跳转动作数组
        url: '', // 上传图片地址
        imageUrl: '', // 图片路径
        menuId: '',
        isCreateOrUpdate: '',
        detailData: [], // 详情
        tag: '',
        actionTag: false,
        actionName: '',
        activeGroup: [], // 关联活动数组
        pageGroup: [], // 关联页面数据
        inputDisabled: false,
        rules: {
          markid: [
            { required: true, message: '请选择广告类型', trigger: 'change' }
          ],
          cadname: [
            { required: true, message: '请输入广告名称', trigger: 'blur, change' }
          ],
          startStopTime: [
            { type: 'array', required: true, message: '请选择起止时间', trigger: 'change' }
          ],
          radioModel: [
            { required: true, message: '请选择动作跳转', trigger: 'change' }
          ],
          equipments: [
            { required: true, message: '请选择所属设备', trigger: 'change' }
          ],
          activeId: [
            { required: true, message: '请选择关联活动', trigger: 'change' }
          ],
          pageId: [
            { required: true, message: '请选择关联页面', trigger: 'change' }
          ]
        },
        imgValid: false,
        imgHost: ''
      }
    },
    methods: {
      searchCustomerType () { // 查询客资类型
        var _data = ''
        getInfo.client(_data, (res) => {
          // console.log(res)
          if (res.message === 'ok') {
            this.customerTypeList = res.content.content
            this.customerTypeLoading = false
          }
        })
      },
      searchAd () { // 查询广告
        var _data = {
          system: '1',
          ad: '1',
          state: '1',
          page: 1,
          pageSize: 10000
        }
        gggl.mkgl.list(_data, (res) => { // 查询广告
          // console.log(res)
          if (res.message === 'ok') {
            this.markidGroup = res.content.content
            // this.equipmentsGroup = res.content.content[0].equipmentName.split(',')
            console.log(this.markidGroup)
          } else {
            this.message('查询失败', 'error')
          }
        })
      },
      markidChange (val) { // 广告类型切换
        console.log(val)
        if (val === '') {
          this.equipmentsGroup = []
          this.basicInfo.equipments = []
          this.basicInfo.equipment = []
        } else {
          for (let i = 0; i < this.markidGroup.length; i++) {
            const ele = this.markidGroup[i]
            if (val === ele.markId) {
              this.equipmentsGroup = []
              // this.equipmentsGroup = this.strToArr(element.equipmentName)
              // this.equipments = this.strToArr(element.equipmentName)
              for (let k = 0; k < ele.equipments.length; k++) {
                const ele2 = ele.equipments[k]
                var a = {}
                console.log(ele.equipmentName.split(',')[k])
                a.name = (ele.equipmentName.split(','))[k]
                a.id = ele2
                console.log(a)
                Vue.set(this.equipmentsGroup, k, a)
                // this.equipmentsGroup.push(a)
              }
            }
          }
        }
        console.log(this.equipmentsGroup)
        // this.matchBusinessType()
      },
      radioChange (val) { // 所属设备切换
        console.log(val)
        this.actionTag = true
        var _data = {
          page: 1,
          pageSize: 10000,
          state: 1,
          system: 1,
          equipment: val
        }
        console.log(_data)
        gggl.dztzgl.list(_data, (res) => {
          console.log(res)
          this.actionGroup = res.content.content
        })
        // console.log(this.equipmentsGroup[])
        for (let index = 0; index < this.equipmentsGroup.length; index++) {
          const element = this.equipmentsGroup[index]
          if (Number(val) === Number(element.id)) {
            this.actionName = element.name
          }
        }
        this.basicInfo.equipment[0] = val
        this.basicInfo.adPicture[0].equipment = val
        // console.log(arguments)
        // this.matchBusinessType()
      },
      searchAction (arr) { // 查询动作
        console.log(arr)
        this.actionGroup = []
        this.actionTag = [false, false, false]
        for (let index = 0; index < arr.length; index++) {
          const element = arr[index]
          var _data = {
            page: 1,
            pageSize: 10000,
            state: 1,
            system: 1,
            equipment: element
          }
          console.log(_data)
          gggl.dztzgl.list(_data, (res) => {
            console.log(res)
            // this.actionGroup[group[index].id] = res.content.content
            // this.actionGroup[index] = res.content.content
            Vue.set(this.actionGroup, element - 1, res.content.content)
          })
          this.actionTag[element - 1] = true
        }
        console.log(this.actionGroup)
        console.log(this.actionTag)
      },
      actionChange (val) { // 动作跳转切换
        console.log(val)
        this.basicInfo.adPicture[0].actiontype = val
        this.actionGroup.forEach(item => {
          if (Number(item.markId) === Number(val)) {
            this.basicInfo.adPicture[0].actionId = item.id
          }
        })
        this.basicInfo.adPicture[0].adurl = ''
        this.basicInfo.activeId = ''
        this.basicInfo.pageId = ''
        this.handleGetAct(val)
      },
      handleGetAct (val) {
        if (val === '10') {
          var _data = {}
          _data.branchId = this.basicInfo.banchid
          _data.userType = this.basicInfo.usertype
          _data.type = 1
          console.log(_data)
          gggl.dhxtgg.banner.getAct(_data, (res) => {
            console.log(res)
            if (res.message === 'ok') {
              this.activeGroup = res.content
            }
          })
          this.inputDisabled = true
        } else if (val === '40') {
          var _dataPage = {
            isDel: 0,
            page: 1,
            pageSize: 1000
          }
          console.log(this.basicInfo.equipments)
          if (Number(this.basicInfo.equipments) === 2) {
            _dataPage.client = 3
          } else if (Number(this.basicInfo.equipments) === 3) {
            _dataPage.client = 2
          } else {
            _dataPage.client = this.basicInfo.equipments
          }
          console.log(_dataPage)
          column.view.list(_dataPage, (res) => {
            console.log(res)
            this.pageGroup = res.content.content
          })
          this.inputDisabled = true
        } else {
          this.inputDisabled = false
        }
      },
      actionSelChange (val) { // 关联活动切换
        this.basicInfo.adPicture[0].adurl = val
      },
      divClick (n) {
        this.tag = n
      },
      handleAvatarSuccess (res, file) { // 上传图片成功
        if (res.message === 'ok') {
          this.imgValid = true
          this.basicInfo.adPicture[this.tag].adimage = res.content.imageUrl
        } else {
          this.imgValid = false
          this.message('上传图片失败', 'error')
        }
      },
      beforeAvatarUpload (file) { // 上传图片之前
        const isLt3M = file.size / 1024 / 1024 < 3
        if (!isLt3M) {
          this.$message.error('上传图片大小不能超过 3MB!')
        }
        return isLt3M
      },
      // radioChange (val, n) { // 跳转动作类型 切换
      //   console.log(arguments)
      //   for (let k = 0; k < this.actionGroup[n].length; k++) {
      //     const ele2 = this.actionGroup[n][k]
      //     if (val === ele2.id) {
      //       this.basicInfo.adPicture[n].actionName = ele2.name
      //       this.basicInfo.adPicture[n].actiontype = ele2.markId
      //     }
      //   }
      // },
      // matchActionId (detail) { // 根据动作markik 和 name 获取id
      //   console.log(detail)
      //   var self = this
      //   setTimeout(() => {
      //     console.log(self.actionGroup)
      //     for (let i = 0; i < self.actionGroup.length; i++) {
      //       var eleD = detail[i]
      //       if (self.actionGroup[i]) {
      //         var eleA = self.actionGroup[i]
      //         for (let k = 0; k < eleA.length; k++) {
      //           const eleAK = eleA[k]
      //           if (eleD.actionname !== '' && eleD.actiontype !== '') {
      //             console.log(eleAK)
      //             if (eleD.actionname === eleAK.name && eleD.actiontype === eleAK.markId) {
      //               // console.log('aa')
      //               // self.radioModel[i] = eleAK.id
      //               // Vue.set(self.radioModel, i, eleAK.id)
      //             }
      //           }
      //         }
      //       }
      //     }
      //     console.log(self.radioModel)
      //   }, 300)
      // },
      searchDetail (row) { // 查询详情
        gggl.dhxtgg.banner.detail({id: row.cid}, (res) => {
          console.log(res, '详情的数据')
          if (res.message === 'ok') {
            this.detailData = res.content
            if (this.branchId === 1) {
              this.brachDisabled = false
              this.basicInfo.banchid = Number(res.content.branchIds)
              this.showBranch = res.content.branchIds
            } else {
              this.brachDisabled = true
              this.basicInfo.banchid = res.content.branchIds
              this.showBranch = res.content.branchName
            }
            this.actionTag = true
            this.actionName = res.content.equipmentName
            this.basicInfo.usertype = res.content.usertype.toString() // 客资类型
            this.basicInfo.markid = res.content.markid // 广告类型
            this.markidChange(res.content.markid)
            this.basicInfo.cadname = res.content.cadname // 广告名称
            this.basicInfo.orderuptime = res.content.orderuptime // 开始时间
            this.basicInfo.offlinetime = res.content.offlinetime // 结束时间
            this.basicInfo.startStopTime = [this.basicInfo.orderuptime, this.basicInfo.offlinetime]
            this.basicInfo.cadmemo = res.content.cadmemo // 备注
            this.basicInfo.equipment.push(res.content.equipments) // 所属设备 显示的值
            this.basicInfo.equipments = res.content.equipments // 所属设备 上传的值
            Vue.set(this.basicInfo.adPicture, 0, res.content.detail[0])
            this.radioChange(res.content.equipments)
            this.basicInfo.radioModel = res.content.detail[0].actiontype.toString() // 跳转方式
            this.handleGetAct(this.basicInfo.radioModel)
            var self = this
            setTimeout(() => {
              self.basicInfo.activeId = res.content.detail[0].adurl.toString()
              self.basicInfo.pageId = res.content.detail[0].adurl.toString()
            }, 500)
            this.imgValid = true
            // Vue.set(this.basicInfo.adPicture, 1, res.content.detail[1])
            // Vue.set(this.basicInfo.adPicture, 2, res.content.detail[2])
            console.log(this.basicInfo.adPicture)
            // this.searchAction(this.strToArr(res.content.equipments))
            // this.matchActionId(res.content.detail) // 跳转方式
            setTimeout(() => {
              self.basicInfo.adPicture.adurl = res.content.adurl // 跳转参数
            }, 10)
            console.log(this.basicInfo)
          } else {
            this.message('查询详情失败', 'error')
          }
        })
      },
      onSubmit (type, formName) { // 创建
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.imgValid === true) {
              const start = new Date(this.basicInfo.orderuptime).getTime()
              const now = new Date().getTime()
              if (start < now) {
                this.$message({
                  showClose: true,
                  message: '开始时间要晚于当前时间',
                  type: 'error'
                })
                return false
              }
              console.log(arguments)
              var _data = this.basicInfo
              // console.log(_data)
              // _data.banchid = [_data.banchid]
              // _data.usertype = [_data.usertype]
              _data.createOrSave = type
              _data.createuser = this.userName
              _data.cid = this.isCreateOrUpdate === 'update' ? this.detailData.cid : ''
              console.log(_data)
              gggl.dhxtgg.banner[this.isCreateOrUpdate](_data, (res) => {
                console.log(res)
                if (res.message === 'ok') {
                  this.message(this.text + '成功', 'success')
                  this.cancel(this.menuId)
                  this.$store.dispatch('bannerState', this.$store.state.updateState.bannerState + 1)
                } else {
                  this.message(this.text + '失败', 'error')
                }
              })
            } else {
              this.message('请上传图片', 'error')
            }
          }
        })
      },
      cancel (id, num) { // 取消
        if (num) {
          this.$confirm('确定要取消？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$store.dispatch('delTab', {id: id})
          }).catch(() => {
          })
        } else {
          this.$store.dispatch('delTab', {id: id})
        }
      },
      daterangeFormat (t) { // 时间段格式化
        this.basicInfo.orderuptime = t[0]
        this.basicInfo.offlinetime = t[1]
      },
      timeDeltSecond (d) { // 时间去秒
        if (d) {
          return d.split(' ')[0]
        }
      },
      strToArr (str) { // 字符串数组转换
        var arr = []
        if (str.length > 1) {
          arr = str.split(',')
        } else {
          arr.push(str)
        }
        return arr
      },
      message (text, type) { // 消息提示
        this.$message({
          showClose: true,
          message: text,
          type: type
        })
      }
    },
    computed: {
      update_state: function () {
        // console.log(state.updateState.dhmState)
        return this.$store.state.updateState.dztzState
      },
      userName: function () {
        if (!this.$store.state.user.info.user_name) {
          this.$store.dispatch('SET_TOKEN')
        }
        return this.$store.state.user.info.user_name
      },
      userId: function () {
        return this.$store.state.user.info.roleid
      },
      branchName: function () {
        return this.$store.state.user.info.branchId === 1 ? '总公司' : this.$store.state.user.info.branchName
      },
      branchId: function () {
        return this.$store.state.user.info.branchId
      },
      deptName: function () {
        return this.$store.state.user.info.parOrgName
      },
      deptId: function () {
        return this.$store.state.user.info.or_org_id
      }
    },
    watch: {
      update_state (curVal, oldVal) {  // 监听 更新状态 查询list
        this.searchList()
      }
    },
    created () {
      this.url = 'http://' + apiHost.newCms + ':20000' + apiURL.goodsSet_uploadImage
      this.imgHost = apiHost.imgHost
      this.searchAd()
      if (this.branchId === 1) {
        this.brachDisabled = false
        this.basicInfo.banchid = this.branchId
        // this.sortInfo.branchId = this.branchId
      } else {
        this.brachDisabled = true
        this.showBranch = this.branchName
        this.basicInfo.banchid = this.branchId
        // this.formInline.branchId = this.branchId
      }
      this.menuId = this.$store.state.tab.menuId
      console.log(this.$store.state.tab)
      if (this.$store.state.tab.uid) {
        if (this.$store.state.tab.menuId === 'bannergl_fz') {
          this.isCreateOrUpdate = 'create'
          this.text = '复制'
        } else {
          this.isCreateOrUpdate = 'update'
          this.text = '编辑'
        }
        this.searchCustomerType() // 查询客资类型
        // this.searchAction() // 查询动作
        this.searchDetail(this.$store.state.tab.uid)
      } else {
        this.isCreateOrUpdate = 'create'
        this.text = '新增'
        // this.searchAction() // 查询动作
        this.searchCustomerType() // 查询客资类型
      }
    }
  }
</script>
